package cn.wolfcode.crm.util;

import cn.wolfcode.crm.query.JSONResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

/*Shiro的FormAuthentivationFilter类是做认证成功或失败的跳转页面操作,
但是登入界面提交方式是ajax,页面跳转不需要自shiro来做,只需要返回json信息
所以重写认证失败和成功执行的操作*/
public class MyFormFilter extends FormAuthenticationFilter{


    /*认证成功,只需要响应json*/
    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        /*响应登入成功的json信息对象*/
        response.getWriter().print(new ObjectMapper().writeValueAsString(new JSONResult()));
        return false;
    }

    /*认证失败操作,响应失败信息,根据不同的失败,封装信息*/
    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        e.printStackTrace();
        /*根据不同的错误,封装信息*/
        String errorMsg = "出现未知的错误,请联系管理员";
        if(e instanceof UnknownAccountException){
            errorMsg = "用户名不存在";
        }else if(e instanceof IncorrectCredentialsException){
            errorMsg = "密码错误";
        }

        try {
            JSONResult result = new JSONResult();
            result.mark(errorMsg);
            //可能会出IO异常
            response.getWriter().print(new ObjectMapper().writeValueAsString(result));
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return false;
    }

    /*顶账号 d=====(￣▽￣*)b*/
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        /*判断是做登入操作*/
        if (isLoginRequest(request,response)) {
            /*获取主体*/
            Subject subject = SecurityUtils.getSubject();
            /*判断主体是否认证状态*/
            if (subject.isAuthenticated()) {
                subject.logout();
            }
        }
        return super.isAccessAllowed(request,response,mappedValue);
    }
}
